package game;

public final class Rules {
	private Rules() {
		super();
	}

	public static void applyRules(Grid grid) {
		Cell[][] cells = grid.getCells();
		for (int i = 0; i < cells.length; i++) {
			for (int j = 0; j < cells[0].length; j++) {
				Cell cell = cells[i][j];
				int aliveNeighbours = grid.neighbourCount(i, j);

				boolean liveToNextGeneration = true;
				liveToNextGeneration = liveToNextGeneration
						&& underPopulation(cell, aliveNeighbours);
				liveToNextGeneration = liveToNextGeneration
						&& liveToNextGeneration(cell, aliveNeighbours);
				liveToNextGeneration = liveToNextGeneration
						&& overCrowding(cell, aliveNeighbours);
				liveToNextGeneration = liveToNextGeneration
						&& reproduction(cell, aliveNeighbours);

				cell.setLiveToNextGeneration(liveToNextGeneration);
			}
		}

		for (int i = 0; i < cells.length; i++) {
			for (int j = 0; j < cells[0].length; j++) {
				Cell cell = cells[i][j];
				cell.setAlive(cell.isLiveToNextGeneration());
			}
		}
	}

	/**
	 * Any live cell with two or three live neighbours lives on to the next
	 * generation.
	 */
	private static boolean liveToNextGeneration(Cell cell, int aliveNeighbours) {
		if (cell.isAlive()) {
			if (aliveNeighbours == 2 || aliveNeighbours == 3) {
				cell.setLiveToNextGeneration(true);
				return true;
			}
		}

		return true;
	}

	/**
	 * Any live cell with fewer than two live neighbours dies, as if caused by
	 * under-population.
	 */
	private static boolean underPopulation(Cell cell, int aliveNeighbours) {
		if (cell.isAlive()) {
			if (aliveNeighbours < 2) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Any live cell with more than three live neighbours dies, as if by
	 * overcrowding.
	 */
	private static boolean overCrowding(Cell cell, int aliveNeighbours) {
		if (cell.isAlive()) {
			if (aliveNeighbours > 3) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Any dead cell with exactly three live neighbours becomes a live cell, as
	 * if by reproduction.
	 */
	private static boolean reproduction(Cell cell, int aliveNeighbours) {
		if (cell.isAlive()) {
			return true;
		}
		
		if (!cell.isAlive()) {
			if (aliveNeighbours == 3) {
				return true;
			}
		}

		return false;
	}
}
